﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DownloadSpeedHelper
{

    public static event Action<double> GetSpeed;
    private long m_size = 0;
    private long m_fullSize = 0;
    
    private long m_lastSize = -1;
    private float m_lastTime = -1;

    private string m_speedStr = "0B/S";

    public void Reset()
    {
        m_size = 0;
        m_fullSize = 0;

        m_lastSize = -1;
        m_lastTime = -1;

        m_speedStr = "0B/S";
    }

    public void SetProgress(long size, long fullSize)
    {
        m_size = size;
        m_fullSize = fullSize;
    }

    public string CalculationSpeed()
    {
        float time = Time.realtimeSinceStartup;
        if (m_lastTime < 0)
        {
            m_lastTime = time;
            m_lastSize = m_size;

            return m_speedStr;
        }

        float diffTime = time - m_lastTime;
        if (diffTime > 0.2)
        {
            double speed = ((double)(m_size - m_lastSize)) / diffTime;
            GetSpeed?.Invoke(speed/1024);

            m_speedStr = Size2Str(speed) + "/S";

            m_lastTime = time;
            m_lastSize = m_size;
        }

        return m_speedStr;
    }

    public static string Size2Str(double size)
    {
        string sizeStr = null;
        //if (size < 1048576)
        if (size < 524288)
        {
            sizeStr = $"{size / 1024:0.00}K";
        }
        else
        {
            sizeStr = $"{size / 1048576:0.00}M";
        }
        return sizeStr;
    }
}
